namespace Ordering.Domain.Orders;

public class Order
{
    private readonly List<OrderItem> _items = [];

    private Order()
    {
    }

    public Order(
        Guid userId,
        IEnumerable<OrderItem> items,
        string? shippingAddress,
        string? notes)
    {
        UserId = userId;
        ShippingAddress = shippingAddress;
        Notes = notes;
        Status = OrderStatus.Pending;
        CreatedAt = DateTime.UtcNow;

        if (items is null)
        {
            throw new ArgumentNullException(nameof(items));
        }

        var materialized = items.ToList();
        if (materialized.Count == 0)
        {
            throw new ArgumentException("Order requires at least one item", nameof(items));
        }

        _items = materialized;
        Total = _items.Sum(i => i.TotalPrice);
    }

    public Guid Id { get; private set; } = Guid.NewGuid();

    public Guid UserId { get; private set; }

    public string Status { get; private set; } = OrderStatus.Pending;

    public decimal Total { get; private set; }

    public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;

    public string? ShippingAddress { get; private set; }

    public string? Notes { get; private set; }

    public IReadOnlyCollection<OrderItem> Items => _items.AsReadOnly();

    public void Paid()
    {
        Status = OrderStatus.Paid;
    }

    public void Cancelled()
    {
        Status = OrderStatus.Cancelled;
    }
}
